package init

import (
	"log"
	"os"

	"frame/global/consts"
	"frame/global/variable"
	carbonfactory "frame/pkg/utils/carbon"
	gormv2 "frame/pkg/utils/gorm"
	"frame/pkg/utils/yml_config"
	"frame/pkg/utils/zap_factory"
	"github.com/panjf2000/ants/v2"
	"go.uber.org/zap/zapcore"
)

func checkRequiredFolders() {
	requiredFolders := []struct {
		path string
		err  string
	}{
		{path: variable.BasePath + "/config/config.yml", err: consts.ErrorsConfigYamlNotExists},
	}

	for _, folder := range requiredFolders {
		if _, err := os.Stat(folder.path); err != nil {
			log.Fatal(folder.err + err.Error())
		}
	}

}
func initializeGorm() {
	config := variable.ConfigGormYml
	if config.GetInt("Gorm.Mysql.IsInitGlobalGormMysql") == 1 {
		if dbMysql, err := gormv2.GetOneMysqlClient(); err != nil {
			log.Fatal(consts.ErrorsGormInitFail + err.Error())
		} else {
			variable.GormDbMysql = dbMysql

		}
	}

}
func initializeConfigAndLogs() {
	variable.ConfigYml = yml_config.CreateYamlFactory()
	variable.ConfigYml.ConfigFileChangeListen()
	variable.ConfigGormYml = variable.ConfigYml.Clone("gorm_v2")
	variable.ConfigGormYml.ConfigFileChangeListen()

	ZapLogHandler := func(entry zapcore.Entry) error {
		go func(paramEntry zapcore.Entry) {
			// 处理系统日志
		}(entry)
		return nil
	}

	variable.ZapLog = zap_factory.CreateZapFactory(ZapLogHandler)

}
func initializePool() {
	var err error
	variable.AntsPool, err = ants.NewPool(variable.ConfigYml.GetInt("Pool.Size"))
	if err != nil {
		log.Fatal(consts.ErrorsInitAntsPoolFail + err.Error())
	}

}

func initializeCaron() {
	carbonfactory.InitGlobalTimeZone()

	//variable.ZapLog.Info("当前时区", zap.String("time_zone", variable.ConfigYml.GetString("TimeZone")))
	//variable.ZapLog.Info("当前时间", zap.Any("locale time", carbon.Now()))

}
func init() {

	// 初始化配置文件和全局日志
	initializeConfigAndLogs()

	//检查必要文件是否存在
	checkRequiredFolders()

	// 初始化协程池
	initializePool()

	// 时间初始化 全局时区等
	initializeCaron()

	// 初始化Gorm数据库连接
	initializeGorm()

}
